package com.mzx.javase.thread.synchro;

/**
 * 类描述：解决线程同步的第二种方法，使用同步方法
 * 同步方法使用synchronized修饰的方法
 *
 * @ClassName ThreadTest02
 * @Description TODO
 * @Author 马子鑫
 * @Date 2022/8/4 20:54
 * @Version 1.0
 */
public class ThreadTest02 {
    public static void main(String[] args) {
        TicketThread1 ticketThread = new TicketThread1();
        Thread t1 = new Thread(ticketThread, "窗口1");
        Thread t2 = new Thread(ticketThread, "窗口2");
        Thread t3 = new Thread(ticketThread, "窗口3");
        t1.start();
        t2.start();
        t3.start();
    }
}

class TicketThread1 implements Runnable {

    private int ticketNum = 200;

    @Override
    public void run() {
        //用synchronized修饰方法
        while (true) {
            //卖票
            sellTicket();
        }
    }

    /**
     * 锁对象，谁调用这个方法，就是谁
     * 隐含的对象就是this
     *
     * 静态方法，隐含锁对象就是TicketThread1.class
     */
    public synchronized void sellTicket() {
        if (ticketNum > 0) {
            System.out.println(Thread.currentThread().getName() + "还剩余:" + ticketNum--);
        }
    }
}


